<template>
  <view class="refund-page">
    <view class="header">
      <text class="title">申请退款</text>
    </view>
    
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <view v-else-if="orderInfo" class="refund-content">
      <!-- 订单信息 -->
      <view class="order-section">
        <view class="section-title">订单信息</view>
        <view class="order-info">
          <view class="info-item">
            <text class="label">订单号</text>
            <text class="value">{{ orderInfo.orderNo }}</text>
          </view>
          <view class="info-item">
            <text class="label">订单金额</text>
            <text class="value price">¥{{ orderInfo.totalAmount }}</text>
          </view>
          <view class="info-item">
            <text class="label">支付时间</text>
            <text class="value">{{ formatTime(orderInfo.payTime) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 退款金额 -->
      <view class="amount-section">
        <view class="section-title">退款金额</view>
        <view class="amount-input">
          <text class="currency">¥</text>
          <input 
            class="amount-field" 
            type="digit" 
            v-model="refundAmount" 
            placeholder="请输入退款金额"
            @input="onAmountInput"
          />
        </view>
        <view class="amount-tips">
          <text>可退款金额：¥{{ maxRefundAmount }}</text>
        </view>
      </view>
      
      <!-- 退款原因 -->
      <view class="reason-section">
        <view class="section-title">退款原因</view>
        <view class="reason-options">
          <view 
            class="reason-item" 
            :class="{ active: selectedReason === reason.value }"
            v-for="reason in refundReasons" 
            :key="reason.value"
            @click="selectReason(reason.value)"
          >
            <text>{{ reason.label }}</text>
          </view>
        </view>
        <view class="custom-reason" v-if="selectedReason === 'other'">
          <textarea 
            class="reason-textarea" 
            v-model="customReason" 
            placeholder="请输入具体退款原因"
            maxlength="200"
          ></textarea>
          <text class="char-count">{{ customReason.length }}/200</text>
        </view>
      </view>
      
      <!-- 联系方式 -->
      <view class="contact-section">
        <view class="section-title">联系方式</view>
        <view class="contact-input">
          <input 
            class="contact-field" 
            type="text" 
            v-model="contactPhone" 
            placeholder="请输入联系电话"
          />
        </view>
      </view>
      
      <!-- 提交按钮 -->
      <view class="submit-section">
        <button class="submit-btn" :disabled="!canSubmit" @click="submitRefund">
          提交退款申请
        </button>
      </view>
    </view>
    
    <view v-else class="error">
      <text>订单信息不存在</text>
    </view>
  </view>
</template>

<script>
import { payService } from '@/services/pay.js'

export default {
  data() {
    return {
      orderId: '',
      paymentId: '',
      orderInfo: null,
      loading: true,
      refundAmount: '',
      selectedReason: '',
      customReason: '',
      contactPhone: '',
      refundReasons: [
        { value: 'quality', label: '商品质量问题' },
        { value: 'damage', label: '商品损坏' },
        { value: 'wrong', label: '商品与描述不符' },
        { value: 'size', label: '尺寸不合适' },
        { value: 'delivery', label: '配送问题' },
        { value: 'duplicate', label: '重复下单' },
        { value: 'change', label: '改变主意' },
        { value: 'other', label: '其他原因' }
      ]
    }
  },
  
  computed: {
    maxRefundAmount() {
      return this.orderInfo ? this.orderInfo.totalAmount : 0
    },
    
    canSubmit() {
      return this.refundAmount && 
             parseFloat(this.refundAmount) > 0 && 
             parseFloat(this.refundAmount) <= this.maxRefundAmount &&
             this.selectedReason &&
             this.contactPhone
    }
  },
  
  onLoad(options) {
    this.orderId = options.orderId
    this.paymentId = options.paymentId
    this.loadOrderInfo()
  },
  
  methods: {
    async loadOrderInfo() {
      try {
        const res = await payService.getOrderPaymentInfo(this.orderId)
        
        if (res.success) {
          this.orderInfo = res.data
        } else {
          uni.showToast({
            title: res.message || '获取订单信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取订单信息失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    onAmountInput(e) {
      const value = e.detail.value
      const numValue = parseFloat(value)
      
      if (numValue > this.maxRefundAmount) {
        this.refundAmount = this.maxRefundAmount.toString()
        uni.showToast({
          title: '退款金额不能超过订单金额',
          icon: 'none'
        })
      }
    },
    
    selectReason(reason) {
      this.selectedReason = reason
      if (reason !== 'other') {
        this.customReason = ''
      }
    },
    
    async submitRefund() {
      if (!this.canSubmit) return
      
      const reason = this.selectedReason === 'other' ? this.customReason : this.selectedReason
      
      uni.showModal({
        title: '确认退款',
        content: `确定要申请退款 ¥${this.refundAmount} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.doSubmitRefund(reason)
          }
        }
      })
    },
    
    async doSubmitRefund(reason) {
      uni.showLoading({
        title: '提交中...'
      })
      
      try {
        const params = {
          orderId: this.orderId,
          paymentId: this.paymentId,
          refundAmount: parseFloat(this.refundAmount),
          refundReason: reason,
          contactPhone: this.contactPhone
        }
        
        const res = await payService.applyRefund(params)
        
        if (res.success) {
          uni.hideLoading()
          uni.showToast({
            title: '退款申请提交成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.hideLoading()
          uni.showToast({
            title: res.message || '退款申请失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('退款申请失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },
    
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.refund-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .header {
    background-color: #fff;
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .loading, .error {
    text-align: center;
    padding: 200rpx 0;
    color: #999;
    font-size: 28rpx;
  }
  
  .refund-content {
    .order-section, .amount-section, .reason-section, .contact-section {
      background-color: #fff;
      margin-bottom: 20rpx;
      padding: 30rpx;
      
      .section-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 30rpx;
      }
    }
    
    .order-info {
      .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 28rpx;
          color: #666;
        }
        
        .value {
          font-size: 28rpx;
          color: #333;
          
          &.price {
            color: #ff4d4f;
            font-weight: bold;
          }
        }
      }
    }
    
    .amount-input {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #eee;
      padding-bottom: 20rpx;
      margin-bottom: 20rpx;
      
      .currency {
        font-size: 36rpx;
        color: #ff4d4f;
        margin-right: 20rpx;
      }
      
      .amount-field {
        flex: 1;
        font-size: 36rpx;
        color: #333;
      }
    }
    
    .amount-tips {
      font-size: 24rpx;
      color: #999;
    }
    
    .reason-options {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 30rpx;
      
      .reason-item {
        width: calc(50% - 10rpx);
        height: 80rpx;
        border: 1rpx solid #ddd;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 20rpx;
        font-size: 28rpx;
        color: #666;
        
        &:nth-child(odd) {
          margin-right: 20rpx;
        }
        
        &.active {
          border-color: #007aff;
          background-color: #e6f7ff;
          color: #007aff;
        }
      }
    }
    
    .custom-reason {
      position: relative;
      
      .reason-textarea {
        width: 100%;
        height: 200rpx;
        border: 1rpx solid #ddd;
        border-radius: 8rpx;
        padding: 20rpx;
        font-size: 28rpx;
        color: #333;
        box-sizing: border-box;
      }
      
      .char-count {
        position: absolute;
        bottom: 20rpx;
        right: 20rpx;
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .contact-input {
      .contact-field {
        width: 100%;
        height: 80rpx;
        border: 1rpx solid #ddd;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        color: #333;
        box-sizing: border-box;
      }
    }
    
    .submit-section {
      padding: 40rpx;
      
      .submit-btn {
        width: 100%;
        height: 88rpx;
        background-color: #007aff;
        color: #fff;
        border-radius: 44rpx;
        font-size: 32rpx;
        border: none;
        
        &:disabled {
          background-color: #ccc;
        }
      }
    }
  }
}
</style> 